package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author alexis
 * @date 2025-10-16
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警数据过滤
     */
    @Override
    public void alertFilter() {
        //查询判断规则
        Long count = lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (count <= 0) {
            return;
        }
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        //解析设备数据
        List<DeviceData> alertDataList = new ArrayList<>();
        values.forEach(o -> {
            alertDataList.addAll(JSONUtil.toList(o.toString(), DeviceData.class));
        });
        alertDataList.forEach(this::alertFilter);
    }

    /**
     * 报警数据过滤
     *
     * @param deviceData 报警数据
     */
    private void alertFilter(DeviceData deviceData) {
        //校验上报时间是否小于一分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        //查询单个设备规则
        List<AlertRule> alertRules = lambdaQuery()
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .list();
        //查询全部设备规则
        List<AlertRule> alertRules1 = lambdaQuery().eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .list();
        //合并设备规则
        Collection<AlertRule> allAlertRules = CollUtil.addAll(alertRules, alertRules1);
        //判断是否为空
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }
        //按照过滤规则和上报的数据进行匹配
        allAlertRules.forEach(alertRule -> {
            deviceDataAlarmHandler(alertRule, deviceData);
        });
    }

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;
    /**
     * 设备数据处理
     *
     * @param rule       设备规则
     * @param deviceData 设备数据
     */
    private void deviceDataAlarmHandler(AlertRule rule, DeviceData deviceData) {
        //判断是否在生效时间内
        String alertEffectivePeriod = rule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime time = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        if (!time.isAfter(startTime) || !time.isBefore(endTime)) {
            return;
        }
        //判断是否达到阈值
        Double value = rule.getValue();
        String operator = rule.getOperator();
        //获取IOTID
        String iotId = deviceData.getIotId();
        //统计次数的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        //两个参数x,y(参数有顺序要求，左边是上报的数据，后边是规则的数据)  x==y 返回0  x>y 返回大于0  x<y 返回小于0的数值
        int compare = NumberUtil.compare(Double.parseDouble(deviceData.getDataValue()), value);
        if ((operator.equals(">=") && compare >= 0) || (operator.equals("<") && compare < 0)) {
            log.info("设备数据：{} 触发报警规则：{}", deviceData, rule);
        } else {
            redisTemplate.delete(aggCountKey);
            return;
        }
        //查询沉默周期
        String silentPeriod = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        String silentData = redisTemplate.opsForValue().get(silentPeriod);
        if (StringUtils.isNotEmpty(silentData)) {
            return;
        }
        //从redis中获取报警次数
        String count = redisTemplate.opsForValue().get(aggCountKey);
        //计算当前报警次数
        int countNum = StringUtils.isEmpty(count) ? 1 : Integer.parseInt(count) + 1;
        //报警次数是否等于持续周期
        if(ObjectUtil.notEqual(rule.getDuration(), countNum)){
            //报警次数加一
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(countNum));
            return;
        }
        redisTemplate.delete(aggCountKey);
        //添加redis沉默周期
        redisTemplate.opsForValue().set(silentPeriod, "1", rule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //是否是老人数据
        List<Long> userId = new ArrayList<>();
        if (rule.getAlertDataType() == 0) {
            //是否是固定设备
            if(deviceData.getLocationType() == 1){
                //通过床位查老人，然后根据老人ID查护理员
                userId=deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
            //根据老人ID查询护理员
            userId= deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
        }else if (rule.getAlertDataType() == 1) {
            //查询护理员
            userId= sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        //查询超级管理员
        userId.addAll(sysUserRoleMapper.selectUserIdByRoleName("超级管理员"));
        //去重
        userId = CollUtil.distinct(userId);
        //批量保存报警数据
        insertBatch(userId, rule, deviceData);
    }

    /**
     * 批量保存报警数据
     *
     * @param userId     用户ID
     * @param rule       设备规则
     * @param deviceData 设备数据
     */
    private void insertBatch(List<Long> userId, AlertRule rule, DeviceData deviceData) {
        //创建报警数据
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setType(rule.getAlertDataType());
        alertData.setStatus(0);
        //获取userid中的数据
        List<AlertData> collect = userId.stream().map(id -> {
            AlertData alertData1 = BeanUtil.toBean(alertData, AlertData.class);
            alertData1.setId(null);
            alertData1.setUserId(id);
            alertData1.setCreateTime(new Date());
            return  alertData1;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(collect);
    }

}
